<template>
  <basic-container>
    <div :key="key" class="search-container" style="display: block"></div>
    <el-tabs type="border-card" v-model="tabsIndex" @tab-click="handleTabClick" :before-leave="beforeLeave">
      <el-tab-pane label="客户明细" name="1"> </el-tab-pane>
      <el-tab-pane label="物料对照表" name="2"></el-tab-pane>
      <el-tab-pane label="批次对照表" name="3"></el-tab-pane>
    </el-tabs>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :search.sync="query"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      :key="key"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @row-click="rowClick"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @size-change="sizeChange"
      @current-change="currentChange"
      @refresh-change="refreshChange"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.customerExtension_add && tabsIndex === '1'" @click="handleAddBtn()">新 增</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.customerExtension_delete && tabsIndex === '1'" @click="handleDelete()">删 除 </el-button>
        <el-button type="success" size="small" icon="el-icon-upload2" v-if="tabsIndex !== '1' && permission.customerExtension_import" @click="handleImport()"> 导 入 </el-button>
      </template>
      <template slot="menu" slot-scope="{ row }">
        <el-button icon="el-icon-view" size="small" type="text" v-if="permission.customerExtension_view && tabsIndex === '1'" @click="handleViewBtn(row)">查看</el-button>
        <el-button icon="el-icon-edit" size="small" type="text" v-if="permission.customerExtension_edit && tabsIndex === '1'" @click="handleEditBtn(row)">编辑</el-button>
        <el-button icon="el-icon-delete" size="small" type="text" v-if="permission.customerExtension_delete" @click="$refs.crud.rowDel(row, index)">删除</el-button>
        <!-- <el-button type="text" size="small" @click="tabJump('2', row)">物料对照表维护</el-button>
        <el-button type="text" size="small" @click="tabJump('3', row)">批次对照表维护</el-button> -->
      </template>
      <template slot="partNoForm">
        <el-input placeholder="请选择 内部物料编码" v-model="form.partNo" class="input-with-select" disabled>
          <el-button
            slot="append"
            icon="el-icon-circle-close"
            v-if="form.partNo"
            @click="
              form.partNo = '';
              form.partName = '';
              form.partModel = '';
              form.partMasterId = '';
            "
          ></el-button>
          <el-button slot="append" icon="el-icon-search" @click="openPartModal()"></el-button>
        </el-input>
      </template>
      <template slot="partnerNoForm">
        <el-input placeholder="请选择 客户编码" v-model="form.partnerNo" class="input-with-select" disabled>
          <el-button
            slot="append"
            icon="el-icon-circle-close"
            v-if="form.partnerNo"
            @click="
              form.partnerNo = '';
              form.partnerName = '';
              form.partnerId = '';
            "
          ></el-button>
          <el-button slot="append" icon="el-icon-search" @click="openPartnerModal()"></el-button>
        </el-input>
      </template>
      <!-- <template slot="sequenceDefinitionNameForm">
        <el-input placeholder="请选择 条码规则" v-model="form.sequenceDefinitionName" class="input-with-select" disabled>
          <el-button
            slot="append"
            icon="el-icon-circle-close"
            v-if="form.sequenceDefinitionName"
            @click="
              form.sequenceDefinitionName = '';
              form.sequenceDefinitionId = '';
            "
          ></el-button>
          <el-button slot="append" icon="el-icon-search" @click="openSquenceModal"></el-button>
        </el-input>
      </template>
      <template slot="qcTemplateNameForm">
        <el-input placeholder="请选择OQC检验模板" v-model="form.qcTemplateName" class="input-with-select" disabled>
          <el-button
            slot="append"
            icon="el-icon-circle-close"
            v-if="form.qcTemplateName"
            @click="
              form.qcTemplateName = '';
              form.qcTemplateId = '';
              form.qcTemplateCode = '';
            "
          ></el-button>
          <el-button slot="append" icon="el-icon-search" @click="openOQCModal"></el-button>
        </el-input>
      </template>
      <template slot="oqcRequiredForm">
        <el-switch v-model="form.oqcRequired" @change="handleSwitch($event)"> </el-switch>
      </template> -->
    </avue-crud>
    <el-dialog append-to-body v-if="customerDialog" :visible.sync="customerDialog" :title="dialogTitle" class="customer-dialog">
      <!-- <el-tabs v-model="tabsDialogIndex" @tab-click="handleDialogClick">
        <el-tab-pane label="基本信息" name="baseInfo"></el-tab-pane>
        <el-tab-pane label="特殊要求" name="special" v-if="rollingEnable"></el-tab-pane>
      </el-tabs> -->
      <div class="sail-header-dialog-content">
        <div class="formClass">
          <div class="title-result">
            <div class="title">
              <i class="el-icon-vertical-bar avue-group__icon"></i>
              <h3>基础数据</h3>
            </div>
          </div>
          <avue-form ref="customerRef" :option="customerOption" v-model="form">
            <!-- <template slot="locationName">
            <el-input placeholder="请选择 收货地址" v-model="form.locationName" class="input-with-select" disabled>
              <el-button
                slot="append"
                icon="el-icon-circle-close"
                v-if="form.locationName"
                @click="
                  form.locationName = '';
                  form.locations = [];
                "
              ></el-button>
              <el-button slot="append" icon="el-icon-search" @click="openLocationNameModal"></el-button>
            </el-input>
          </template> -->
            <template slot="info">
              <avue-crud
                ref="infoCrud"
                :table-loading="infoLoading"
                @row-update="rowInfoUpdate"
                :page.sync="infoPage"
                @row-save="rowInfoSave"
                @row-del="rowInfoDel"
                :option="infoOption"
                :data="infoData"
                v-model="infoForm"
                @size-change="sizeInfoChange"
                @current-change="currentInfoChange"
              >
              </avue-crud>
            </template>
          </avue-form>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="dialogTitle === '新增'" size="small" type="primary" @click="submit"><i class="el-icon-circle-plus-outline"></i><span>保 存</span></el-button>
        <el-button v-if="dialogTitle === '编辑'" size="small" type="primary" @click="submit"><i class="el-icon-circle-check"></i><span>修 改</span></el-button>
        <el-button size="small" @click="customerDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <el-dialog :title="tabsIndex === '2' ? '物料对照表导入' : '批次对照表导入'" append-to-body :visible.sync="excelBox" width="555px">
      <avue-form ref="excelFile" :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate" class="el-icon-download el-icon--right">模板下载</el-button>
        </template>
      </avue-form>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import {
  getCustomerList,
  addCustomer,
  getCustomerDetail,
  removeCustomer,
  getCustomerPartList,
  addPartCustomer,
  removePartCustomer,
  getPartCustomerDetail,
  getCustomerLotList,
  addLotCustomer,
  removeLotCustomer,
  getLotCustomerDetail,
  getCustomerShippingList,
  removeLotNo
} from '@/api/admin/customer-extension';
import { mapGetters } from 'vuex';
import { exprot } from '@/api/repair/failureconfig';
import { getParamDetail } from '@/api/system/param';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
export default {
  components: {
    CommonModalTemplate
  },
  data() {
    return {
      tabsIndex: '1',
      tabsDialogIndex: 'baseInfo',
      form: {},
      partnerObj: {},
      tempInfoData: [],
      showDialog: false,
      customerDialog: false,
      excelBox: false,
      rollingEnable: false,
      customerLoadingLock: false,
      tabJumpFlag: false,
      detailForm: {},
      infoModel: {},
      customerForm: {},
      dialogTitle: '新增',
      query: {},
      excelForm: {},
      tabObj: {
        1: '客户明细',
        2: '物料对照表',
        3: '批次对照表'
      },
      loading: true,
      infoLoading: true,
      detailLoading: false,
      params: {}, //详情表参数
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      infoPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      timer: new Date().getTime(),
      key: new Date().getTime(),
      tableOption: {},
      selectionList: [],
      selectionDetailList: [],
      detailData: [],
      data: [],
      option: {
        height: 'calc(100vh - 388px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        border: true,
        index: true,
        indexLabel: '序号',
        searchMenuSpan: 5,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        labelWidth: 190,
        searchLabelWidth: 130,
        selection: true,
        // addBtn: true,
        highlightCurrentRow: true, // 选中高亮
        dialogClickModal: false,
        searchMenuPosition: 'right',
        searchSpan: 6,
        menuWidth: 200,
        menu: true,
        columnBtn: false,
        refreshBtn: false,
        column: []
      },
      customerOption: {
        submitBtn: false,
        emptyBtn: false,
        margin: 20,
        column: []
      },
      customerColumn: [
        {
          label: '客户编码',
          prop: 'code',
          searchOrder: 1,
          search: true,
          rules: [
            {
              required: true,
              message: '请输入客户编码',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '客户名称',
          prop: 'name',
          searchOrder: 2,
          search: true,
          rules: [
            {
              required: true,
              message: '请输入客户名称',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '客户缩写',
          prop: 'abbreviation',
          rules: [
            {
              required: true,
              message: '请输入客户缩写',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '供应商代码',
          prop: 'vendorAbbr'
        },
        {
          label: '联系人',
          prop: 'principal'
        },
        {
          label: '部门/职位',
          prop: 'position'
        },
        {
          label: '联系方式',
          prop: 'contacts'
        },
        {
          label: '保修期(年)',
          prop: 'defaultWarrantyPeriod',
          // type: 'number',
          // precision: 2,
          value: '',
          rules: [
            {
              required: false,
              trigger: 'blur',
              validator: (rule, value, callback) => {
                let reg = /^\d+(?:\.\d{0,2})?$/;
                if (value && Number(value) <= 0) {
                  callback(new Error('保修期需要大于0'));
                } else if (isNaN(value)) {
                  callback(new Error('请输入数字'));
                } else if (value && !reg.test(value)) {
                  callback(new Error('最多保留两位小数'));
                } else {
                  callback();
                }
              }
            }
          ]
        },
        {
          label: '客户地址',
          prop: 'address',
          span: 24,
          row: true
        },
        {
          label: '同步时间',
          prop: 'lastSyncTime',
          search: true,
          type: 'datetime',
          searchSpan: 7,
          display: false,
          searchType: 'daterange',
          value: '',
          format: 'yyyy-MM-dd HH:mm:ss',
          valueFormat: 'yyyy-MM-dd HH:mm:ss',
          startPlaceholder: '开始日期',
          endPlaceholder: '结束日期'
        }
      ],
      customerGroup: [
        {
          label: '收货信息',
          arrow: false,
          prop: 'baseInfo',
          labelWidth: 100,
          display: true,
          icon: 'el-icon-vertical-bar',
          column: [
            {
              labelWidth: 0,
              label: '',
              prop: 'info',
              span: 24,
              hide: true,
              formslot: true
            }
          ]
        }
      ],
      infoData: [
        {
          principal: 11
        }
      ],
      infoForm: {},
      infoOption: {
        selection: false,
        editBtn: true,
        viewBtn: true,
        height: 270,
        border: true,
        menuWidth: 200,
        addBtn: true,
        delBtn: true,
        menu: true,
        tip: false,
        index: true,
        indexLabel: '序号',
        column: [
          {
            label: '联系人',
            prop: 'principal',
            rules: [
              {
                required: true,
                message: '请输入联系人',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '联系方式',
            prop: 'contacts',
            rules: [
              {
                required: true,
                message: '请输入联系方式',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '收货地址',
            prop: 'shippingAddress',
            rules: [
              {
                required: true,
                message: '请输入收货地址',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      partColumn: [
        {
          label: '内部物料编码',
          prop: 'partNo',
          type: 'search',
          searchType: 'input',
          search: true,
          disabled: true,
          formSlot: true,
          appendClick: () => {
            this.openPartModal();
          },
          rules: [
            {
              required: true,
              message: '请选择内部物料编码',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '内部物料名称',
          prop: 'partName',
          disabled: true
        },
        {
          label: '内部物料型号',
          prop: 'partModel',
          disabled: true
        },
        {
          label: '客户物料编码',
          prop: 'customerPartNo',
          search: true
        },
        {
          label: '客户物料型号',
          prop: 'customerPartModel'
        },
        {
          label: '客户物料版本',
          prop: 'customerPartVersion'
        },
        {
          label: '客户物料类型',
          prop: 'customerPartType'
        },
        {
          label: '客户自定义1',
          prop: 'customerField1',
          labelTip: '自定义填写该物料对该客户的对应信息，填写后可用于生成客户条码'
        },
        {
          label: '客户自定义2',
          prop: 'customerField2',
          labelTip: '自定义填写该物料对该客户的对应信息，填写后可用于生成客户条码'
        },
        {
          label: '客户自定义3',
          prop: 'customerField3',
          labelTip: '自定义填写该物料对该客户的对应信息，填写后可用于生成客户条码'
        },
        {
          label: '客户自定义4',
          prop: 'customerField4',
          labelTip: '自定义填写该物料对该客户的对应信息，填写后可用于生成客户条码'
        },
        {
          label: '客户自定义5',
          prop: 'customerField5',
          labelTip: '自定义填写该物料对该客户的对应信息，填写后可用于生成客户条码'
        }
      ],
      lotNoColumn: [
        // {
        //   label: '客户名称',
        //   prop: 'partnerName'
        // },
        // {
        //   label: '客户编码',
        //   prop: 'partnerNo'
        // },
        {
          label: '时间（年/月/年周/日）',
          prop: 'key',
          search: true,
          searchLabelWidth: 180,
          labelTip:
            '填写该客户对应的某个客户年/客户月/客户年周/客户日，填写后可用于生成客户条码。填写内容需与序列号规则配置/系统序列号规则配置中勾选内容相符，即：若勾选客户年，此处应填写年；若勾选客户月，此处应填写月；若勾选客户年周，此处应填写年周；若勾选客户日，此处应填写日；若勾选客户年、客户月、客户年周、客户日，此处应填写年、月、周、日',
          rules: [
            {
              required: true,
              message: '请输入时间',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '批次（D.C.）',
          prop: 'value',
          labelTip: '填写该客户该时间对应批次的唯一值，填写后可用于生成客户条码',
          search: true,
          rules: [
            {
              required: true,
              message: '请输入批次',
              trigger: 'blur'
            }
          ]
        }
      ],

      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '附件上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '模板上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: `/api/mes-admin/customer/part/mapping/import`
          },
          // {
          //   label: '数据覆盖',
          //   prop: 'isCovered',
          //   type: 'switch',
          //   align: 'center',
          //   width: 80,
          //   dicData: [
          //     {
          //       label: '否',
          //       value: 0
          //     },
          //     {
          //       label: '是',
          //       value: 1
          //     }
          //   ],
          //   value: 0,
          //   slot: true,
          //   rules: [
          //     {
          //       required: true,
          //       message: '请选择是否覆盖',
          //       trigger: 'blur'
          //     }
          //   ]
          // },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24
          }
        ]
      }
    };
  },
  mounted() {
    this.option.column = this.customerColumn;
    this.customerOption.column = this.customerColumn;
    this.customerOption.group = this.customerGroup;
    this.$nextTick(() => {
      this.handleSearch();
      this.getRollingParamConfig();
    });
    this.onLoad(this.page, this.query);
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      console.log('permissionList');
      return {
        addBtn: this.vaildData(this.permission.customerExtension_add, false),
        viewBtn: this.vaildData(this.permission.customerExtension_view, false),
        delBtn: this.vaildData(this.permission.customerExtension_delete, false),
        editBtn: this.vaildData(this.permission.customerExtension_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    },
    detailIds() {
      let ids = [];
      this.selectionDetailList.forEach((ele) => {
        ids.push(ele.trackId);
      });
      return ids.join(',');
    }
  },
  methods: {
    currentInfoChange(currentPage) {
      this.infoPage.currentPage = currentPage;
      this.customerDetail();
    },
    sizeInfoChange(pageSize) {
      this.infoPage.pageSize = pageSize;
      this.customerDetail();
    },
    onInfoLoad(page, params = {}) {
      this.infoLoading = true;
      getCustomerShippingList(page.currentPage, page.pageSize, Object.assign(params)).then((res) => {});
    },
    rowInfoSave(row, done, loading) {
      this.infoData.push(row);
      done();
    },
    rowInfoUpdate(row, index, done, loading) {
      this.infoData.forEach((item) => {
        item.principal = row.principal;
        item.contacts = row.contacts;
        item.shippingAddress = row.shippingAddress;
      });
      done();
    },
    rowInfoDel(row, index) {
      this.infoData.splice(index, 1);
    },
    handleDialogClick() {
      this.tabsToggle();
    },
    tabsToggle() {
      // if (this.tabsDialogIndex === 'baseInfo') {
      //   this.customerOption.column = this.customerColumn;
      // } else {
      //   this.customerOption.column = [
      //     {
      //       label: '滚动发料-华为要求',
      //       prop: 'rollingEnabled',
      //       type: 'switch',
      //       labelWidth: 160,
      //       labelTip: '客户启动滚动发料后，在仓库备料拣货出库时会进行滚动发料',
      //       dicData: [
      //         {
      //           label: '否',
      //           value: false
      //         },
      //         {
      //           label: '是',
      //           value: true
      //         }
      //       ]
      //     }
      //   ];
      // }
    },
    beforeLeave() {
      if (this.selectionList.length > 1 && this.tabsIndex == '1') {
        this.$message({
          type: 'warning',
          message: '只能选择一条数据'
        });
        this.tabJumpFlag = false;
        return false;
      }

      if (this.selectionList.length == 0 && this.tabsIndex == '1') {
        this.$message({
          type: 'warning',
          message: '请选择客户'
        });
        this.tabJumpFlag = false;
        return false;
      }

      if (this.selectionList.length == 1 && this.tabsIndex == '1') {
        this.partnerObj = this.selectionList[0];
        this.tabJumpFlag = true;
        return true;
      }
    },
    handleSwitch(value) {
      if (!value) {
        this.$set(this.form, 'qcTemplateName', '');
        this.form.qcTemplateCode = '';
        this.form.qcTemplateId = '';
      }
    },
    handleImport() {
      this.excelBox = true;
    },
    async handleTemplate() {
      const data = {
        originalName: `${this.tabsIndex === '2' ? '物料对照表' : '批次对照表'}.xlsx`,
        attachType: 'EXCEL'
      };
      const res = await exprot({ data });
      const blob = new Blob([res.data]);
      const fileName = `${this.tabsIndex === '2' ? '物料对照表' : '批次对照表'}.xlsx`;
      const link = document.createElement('a');
      link.download = fileName;
      link.style.display = 'none';
      link.href = URL.createObjectURL(blob);
      document.body.append(link);
      link.click();
      URL.revokeObjectURL(link.href);
      document.body.removeChild(link);
    },
    structuralSplit() {
      if ($('.informationLabel').length === 0) {
        let card = $('#app .el-card .is-never-shadow');
        let searchSon = $(card[0]).find('.avue-form');
        let searchFather = document.createElement('div');
        searchFather.className = 'informationLabel el-tabs el-tabs--top el-tabs--border-card';
        searchFather.innerHTML = `<div class="el-tabs__header is-top">
              <div class="el-tabs__content" style="padding: 10px 10px 0 10px;background-color: #ffffff;"></div>
            </div>`;
        $(searchFather).find('.el-tabs__content').append(searchSon);
        $('#app .avue-crud__search .el-card__body').append(searchFather);
      }
    },
    uploadAfter(res, done, loading, column) {
      done();
      if (res && res.data.code == 400) {
      } else {
        this.excelBox = false;
        this.refreshChange();
      }
      this.$refs.excelFile.resetFields();
    },
    handleSearch() {
      this.$nextTick(() => {
        this.structuralSplit();
        let searchEls = document.querySelector('.avue-crud__search');
        let rowEl = document.querySelector('.search-container');
        rowEl.append(searchEls);
      });
    },
    // addCrudTitle() {
    //   let crudMenu = document.querySelector('.avue-crud__menu');
    //   let crudTitle = document.querySelector('.crud-title');
    //   crudMenu.appendChild(crudTitle);
    // },
    syncTimeDisplay(bool) {
      // let syncTime = this.findObject(this.customerOption.column, 'syncTime');
      // syncTime.display = bool;
    },
    handleAddBtn() {
      // this.tabsDialogIndex = 'baseInfo';
      // this.tabsToggle();
      // this.syncTimeDisplay(false);
      this.dialogTitle = '新增';
      this.form = {};
      this.infoData = [];
      this.customerDialog = true;
      this.$nextTick(() => {
        this.$refs.customerRef.allDisabled = false;
      });
      this.infoLoading = false;
    },
    handleViewBtn(row) {
      this.form = row;
      var object = {
        1: 'customerDetail',
        2: 'partNoDetail',
        3: 'lotNoDetail'
      };
      this[object[this.tabsIndex]]();
      // this.tabsDialogIndex = 'baseInfo';
      // this.tabsToggle();
      // this.syncTimeDisplay(true);
      this.dialogTitle = '查看';
      this.customerDialog = true;
      this.$nextTick(() => {
        this.$refs.customerRef.allDisabled = true;
      });
    },
    handleEditBtn(row) {
      this.form = row;
      var object = {
        1: 'customerDetail',
        2: 'partNoDetail',
        3: 'lotNoDetail'
      };
      this[object[this.tabsIndex]]();
      // this.tabsDialogIndex = 'baseInfo';
      // this.tabsToggle();
      // this.syncTimeDisplay(false);
      this.dialogTitle = '编辑';
      this.customerDialog = true;
      this.$nextTick(() => {
        this.$refs.customerRef.allDisabled = false;
      });
    },
    customerDetail() {
      this.infoLoading = true;
      getCustomerDetail(this.infoPage.currentPage, this.infoPage.pageSize, this.form.id).then((res) => {
        let data = res.data.data || {};
        this.form = data;
        if (this.form.defaultWarrantyPeriod && Number(this.form.defaultWarrantyPeriod) === 0) {
          this.form.defaultWarrantyPeriod = '';
        }
        console.log(this.form, 'this.form');
        this.infoData = data.page.records || [];
        this.infoPage.total = data.page.total;
        this.tempInfoData = this._cloneDeep(this.tempInfoData.concat(data.page.records));
        this.infoLoading = false;
      });
    },
    partNoDetail() {
      getPartCustomerDetail(this.form.id).then((res) => {
        let data = res.data.data || {};
        data.options = typeof data.options === 'string' ? JSON.parse(data.options) : {};
        this.form = {
          ...data,
          ...data.options
        };
      });
    },
    partNoDetail() {
      getLotCustomerDetail(this.form.id).then((res) => {
        let data = res.data.data || {};
        this.form = data;
      });
    },
    lotNoDetail() {},
    tabJump(index, row) {
      this.query = {};
      if (this.tabsIndex === '1') {
        this.partnerObj = row;
      }
      this.tabsIndex = index;
      var object = {
        1: 'jumpCustomerTab',
        2: 'jumpPartNoTab',
        3: 'jumpLotNoTab'
      };
      this.handleSearch();
      this[object[this.tabsIndex]]();
    },
    handleTabClick() {
      if (this.tabJumpFlag) {
        this.query = {};
        var object = {
          1: 'jumpCustomerTab',
          2: 'jumpPartNoTab',
          3: 'jumpLotNoTab'
        };
        this.handleSearch();
        this[object[this.tabsIndex]]();
      }
    },
    jumpCustomerTab() {
      this.option.addBtn = false;
      this.option.editBtn = false;
      this.option.viewBtn = false;
      this.option.column = this.customerColumn;
      this.customerOption.column = this.customerColumn;
      this.page = {
        pageSize: 20,
        currentPage: 1,
        total: 0
      };
      this.onLoad(this.page, this.query);
    },
    jumpPartNoTab() {
      this.option.addBtn = true;
      this.option.editBtn = true;
      this.option.viewBtn = true;
      this.option.column = this.partColumn;
      this.page = {
        pageSize: 20,
        currentPage: 1,
        total: 0
      };
      this.onPartNoLoad(this.page);
      let excelFile = this.findObject(this.excelOption.column, 'excelFile');
      excelFile.action = `/api/mes-admin/customer/part/mapping/import?customerId=${this.partnerObj.id}`;
    },
    jumpLotNoTab() {
      this.option.addBtn = true;
      this.option.editBtn = true;
      this.option.viewBtn = true;
      this.option.column = this.lotNoColumn;
      this.page = {
        pageSize: 20,
        currentPage: 1,
        total: 0
      };
      this.onLotNoLoad(this.page);
      let excelFile = this.findObject(this.excelOption.column, 'excelFile');
      excelFile.action = `/api/mes-admin/customer/date/code/mapping/import?customerId=${this.partnerObj.id}`;
    },
    submit() {
      this.$refs.customerRef.validate((valid, done) => {
        if (valid) {
          this.addCustomer(this._cloneDeep(this.form), done);
        }
        done();
      });
    },

    addCustomer(row, done, loading) {
      row.customerAddressSubmitDtoList = this._cloneDeep(this.infoData);
      let ids = this.infoData.filter((item) => !!item.id).map((item) => item.id);
      if (!row.deletedCustomerAddrIds) {
        row.deletedCustomerAddrIds = [];
      }
      this.tempInfoData.forEach((item) => {
        if (!ids.includes(item.id)) {
          row.deletedCustomerAddrIds.push(item.id);
        }
      });
      addCustomer(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.customerDialog = false;
          done();
        },
        (error) => {
          // loading();
          window.console.log(error);
        }
      );
    },
    addPartNo(row, done, loading) {
      row.customerId = this.partnerObj.id;
      row.customerCode = this.partnerObj.code;
      row.customerName = this.partnerObj.name;
      row.options = {
        customerField1: this.form.customerField1,
        customerField2: this.form.customerField2,
        customerField3: this.form.customerField3,
        customerField4: this.form.customerField4,
        customerField5: this.form.customerField5
      };
      addPartCustomer(row).then(
        () => {
          this.onPartNoLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    addLotNo(row, done, loading) {
      row.customerId = this.partnerObj.id;
      row.customerCode = this.partnerObj.code;
      row.customerName = this.partnerObj.name;
      addLotCustomer(row).then(
        () => {
          this.onLotNoLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },

    rowUpdate(row, index, done, loading) {
      let object = {
        1: 'addCustomer',
        2: 'addPartNo',
        3: 'addLotNo'
      };
      this[object[this.tabsIndex]](row, done, loading);
    },
    rowSave(row, done, loading) {
      let object = {
        1: 'addCustomer',
        2: 'addPartNo',
        3: 'addLotNo'
      };
      this[object[this.tabsIndex]](row, done, loading);
    },

    delCustomer(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removeCustomer([row.id]);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    delPartNo(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removePartCustomer(row.id);
        })
        .then(() => {
          this.onPartNoLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    delLotNo(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removeLotCustomer(row.id);
        })
        .then(() => {
          this.onLotNoLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    delCustomers() {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removeCustomer(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    delPartNos() {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removePartCustomer(this.ids);
        })
        .then(() => {
          this.onPartNoLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    delLotNos() {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removeLotNo(this.ids);
        })
        .then(() => {
          this.onLotNoLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    rowDel(row) {
      let object = {
        1: 'delCustomer',
        2: 'delPartNo',
        3: 'delLotNo'
      };
      this[object[this.tabsIndex]](row);
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      let object = {
        1: 'delCustomers',
        2: 'delPartNos',
        3: 'delLotNos'
      };
      this[object[this.tabsIndex]]();
    },
    handleRowDelete({ $index }) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.infoData.splice($index, 1);
      });
    },
    beforeOpen(done, type) {
      if (['add', 'edit', 'view'].includes(type)) {
        if (this.tabsIndex === '1') {
          // this.getParamConfig();
        }
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      let object = {
        1: 'customerSearch',
        2: 'partNoSearch',
        3: 'lotNoSearch'
      };
      console.log(params, 'params');
      this.page.currentPage = 1;
      this[object[this.tabsIndex]](params);
      done();
    },
    customerSearch(params) {
      if (params.lastSyncTime) {
        params.startSyncTime = params.lastSyncTime[0];
        params.endSyncTime = params.lastSyncTime[0];
        delete params.lastSyncTime;
      }

      this.onLoad(this.page, params);
    },
    partNoSearch(params) {
      this.query = params;
      this.onPartNoLoad(this.page, params);
    },
    lotNoSearch(params) {
      this.query = params;
      this.onLotNoLoad(this.page, params);
    },
    selectionChange(list) {
      let len = list.length - 1;
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      if (this.tabsIndex == 1) {
        this.onLoad(this.page, this.query);
      } else if (this.tabsIndex == 2) {
        this.onPartNoLoad(this.page, this.query);
      } else {
        this.onLotNoLoad(this.page, this.query);
      }
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      if (this.tabsIndex == 1) {
        this.onLoad(this.page, this.query);
      } else if (this.tabsIndex == 2) {
        this.onPartNoLoad(this.page, this.query);
      } else {
        this.onLotNoLoad(this.page, this.query);
      }
    },
    refreshChange() {
      if (this.tabsIndex == 1) {
        this.onLoad(this.page, this.query);
      } else if (this.tabsIndex == 2) {
        this.onPartNoLoad(this.page, this.query);
      } else {
        this.onLotNoLoad(this.page, this.query);
      }
    },
    onLoad(page, params = {}) {
      // params.partnerType = 'CUSTOMER';
      this.loading = true;
      getCustomerList(page.currentPage, page.pageSize, Object.assign(params)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        // this._forEach(this.data, (item) => {
        //   item.customerName = item.name;
        //   item.customerNo = item.partnerNo;
        //   if (item.locationLists && item.locationLists.length > 0) {
        //     item.locationName = item.locationLists.map((el) => el.name).join(',');
        //   }
        //   if (item.startSyncTime && item.endSyncTime) {
        //     item.syncTime = item.startSyncTime + '~' + item.endSyncTime;
        //   } else {
        //     item.syncTime = '';
        //   }
        //   item.guaranteePeriod = item.guaranteePeriod === null ? undefined : item.guaranteePeriod;
        // });
        this.loading = false;
        this.selectionClear();
      });
    },

    onPartNoLoad(page, params = {}) {
      this.loading = true;
      // params.customerPartNo = this.partnerObj.code;
      params.customerId = this.partnerObj.id;
      getCustomerPartList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.data = this.data.map((item) => {
          item.options = typeof item.options === 'string' ? JSON.parse(item.options) : {};
          let obj = {
            ...item,
            ...item.options
          };
          return obj;
        });
        this.loading = false;
        this.selectionClear();
        // this.addCrudTitle();
      });
    },

    onLotNoLoad(page, params = {}) {
      this.loading = true;
      params.customerId = this.partnerObj.id;
      getCustomerLotList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
        // this.addCrudTitle();
      });
    },
    getParamConfig() {
      getParamDetail({
        paramKey: 'mes.admin.rolling_material'
      }).then((res) => {
        let data = res.data.data;
        var oqcRequiredColumn = this.findObject(this.option.column, 'oqcRequired');
        if (this._get(data, 'paramValue') === 'false') {
          oqcRequiredColumn.disabled = true;
        } else {
          oqcRequiredColumn.disabled = false;
        }
      });
    },

    getRollingParamConfig() {
      getParamDetail({
        paramKey: 'mes.admin.rolling_material'
      }).then((res) => {
        let data = res.data.data;
        if (this._get(data, 'paramValue') === 'false') {
          this.rollingEnable = false;
        } else {
          this.rollingEnable = true;
        }
      });
    },

    /**
     * 模态框回调
     */
    getSelectedRows(rowData, titleInfo) {
      switch (titleInfo) {
        case 'partInfo':
          this.$set(this.form, 'partNo', rowData.partNo);
          this.$set(this.form, 'partName', rowData.name);
          this.$set(this.form, 'partModel', rowData.partModel);
          this.form.partMasterId = rowData.id;
          break;
        case 'sequenceInfo':
          this.$set(this.form, 'sequenceDefinitionName', rowData.name);
          this.$set(this.form, 'sequenceDefinitionId', rowData.id);
          break;
        case 'locationInfo':
          let locationNames = rowData.map((item) => item.name);
          let locations = rowData.map((item) => item.id);
          this.$set(this.form, 'locations', locations);
          this.$set(this.form, 'locationName', String(locationNames));
          break;
        case 'OQCInfo':
          this.$set(this.form, 'qcTemplateName', rowData.name);
          this.form.qcTemplateId = rowData.id;
          this.form.qcTemplateCode = rowData.code;
          break;
        case 'partnerInfo':
          this.$set(this.form, 'partnerNo', rowData.partnerNo);
          this.$set(this.form, 'partnerName', rowData.name);
          this.form.partnerId = rowData.id;
          break;
        default:
          break;
      }
    },
    openPartModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '物料数据（双击进行选择）',
        url: '/api/mes-admin/part-master/page',
        isPage: true,
        index: true,
        indexLabel: '序号',
        rowSelectionType: 'single',
        titleInfo: 'partInfo',
        columnDefs: [
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '版本',
            prop: 'revision'
          }
        ]
      };
    },
    /**
     * 供应商信息模态框
     */
    openPartnerModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择客户信息（双击进行选择）',
        url: '/api/mes-admin/partner/page?partnerType=CUSTOMER',
        isPage: true,
        index: true,
        indexLabel: '序号',
        selection: true,
        rowSelectionType: 'single',
        titleInfo: 'partnerInfo',
        columnDefs: [
          {
            label: '编码',
            prop: 'partnerNo',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          }
        ]
      };
    },
    /**
     * 打开序列号模态框
     */
    openSquenceModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择序列号规则信息（双击进行选择）',
        url: `/api/mes-admin/sequencedefinition/page?type=material`,
        isPage: true,
        titleInfo: 'sequenceInfo',
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '大类',
            prop: 'type',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=serial',
            search: true,
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '小类',
            prop: 'subType',
            dicUrl: '/api/blade-system/dict/dictionary?code=material',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            type: 'select',
            search: true
          },
          {
            label: '规则名称',
            prop: 'name',
            search: true
          },
          {
            label: '序列号ID',
            prop: 'code'
          },
          {
            label: '起始流水号',
            prop: 'startSequenceNo'
          },
          {
            label: '结束流水号',
            prop: 'endSequenceNo'
          },
          {
            label: '清零类型',
            prop: 'regressionType',
            type: 'select',
            value: 'yearType',
            dicData: [
              {
                label: '不清零',
                value: ''
              },
              {
                label: '年',
                value: 'yearType'
              },
              {
                label: '月',
                value: 'monthType'
              },
              {
                label: '周',
                value: 'weekType'
              },
              {
                label: '日',
                value: 'dayType'
              }
            ]
          },
          {
            label: '序列号构成规则',
            prop: 'sequenceNoFormat'
          }
        ]
      };
    },
    /**
     * OQC检验模板模态框
     */
    openOQCModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择OQC检验模板（双击进行选择）',
        url: '/api/mes-product/qms-inspection-template/page?type=OQC',
        isPage: true,
        selection: true,
        rowSelectionType: 'single',
        titleInfo: 'OQCInfo',
        columnDefs: [
          {
            label: '模板类型',
            prop: 'type',
            minWidth: 150,
            searchOrder: 1
          },
          {
            label: '检验模板名称',
            minWidth: 150,
            search: true,
            searchOrder: 2,
            searchSpan: 12,
            searchLabelWidth: 150,
            prop: 'name'
          },
          {
            label: '检验模板编码',
            prop: 'code',
            minWidth: 100
          },
          {
            label: '版本号',
            minWidth: 100,
            prop: 'revision'
          },
          {
            label: '备注',
            minWidth: 100,
            prop: 'remark'
          },

          {
            label: '制定人',
            prop: 'createUserName'
          },
          {
            label: '制定时间',
            minWidth: 150,
            prop: 'createTime',
            type: 'datetime'
          }
        ]
      };
    },
    openLocationNameModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择收货地址信息',
        url: '/api/mes-admin/location/page?status=0',
        isPage: true,
        rowSelectionType: 'multiple',
        titleInfo: 'locationInfo',
        columnDefs: [
          {
            label: '地址名称',
            prop: 'name',
            search: true
          },
          {
            label: '国家',
            prop: 'countryName'
          },
          {
            label: '省份',
            prop: 'provinceName'
          },
          {
            label: '城市',
            prop: 'cityName'
          },
          {
            label: '详细地址1',
            prop: 'location1'
          },
          {
            label: '详细地址2',
            prop: 'location2'
          },
          {
            label: '详细地址3',
            prop: 'location3'
          },
          {
            label: '详细地址4',
            prop: 'location4'
          },
          {
            label: '邮编',
            prop: 'postCode'
          },
          {
            label: '经度',
            prop: 'latitude'
          },
          {
            label: '纬度',
            prop: 'longitude'
          }
        ]
      };
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    newCrudKey() {
      this.key = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-tabs--border-card {
  border: none;
}
::v-deep .el-card__body {
  padding: 0;
}
::v-deep .el-tabs__content {
  padding: 0;
}
::v-deep .avue-crud__menu {
  flex-wrap: wrap;
}
.crud-title {
  width: 100%;
}
.customer-dialog {
  ::v-deep .el-dialog__body {
    padding: 0 20px 0px;
  }
}
.formClass {
  margin-top: 20px;
}
.title-result {
  display: flex;
  justify-content: space-between;
  .title {
    display: flex;
    align-items: center;
  }
}

h4 {
  margin-top: 4px;
  margin-bottom: 4px;
}
</style>
